//
//  CommityListViewController.m
//  cityStar
//
//  Created by Hancong on 15/1/1.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "CommityListViewController.h"
#import "FSDropDownMenu.h"
#import "SingleTableView.h"
#import "UIColor+FlatUI.h"
#import "WebViewJavascriptBridge.h"
#import "RepairAndHomeViewController.h"
#import "WaresDetailViewController.h"
#import "HTDefine.h"
#import <CoreLocation/CoreLocation.h>
#import "selectDistrict.h"
#import "INTULocationManager.h"

@interface CommityListViewController ()<FSDropDownMenuDataSource,FSDropDownMenuDelegate,SingleTableViewDelegate,UIWebViewDelegate,CLLocationManagerDelegate>
@property (nonatomic,weak) IBOutlet UIButton *btnAddress;
@property (nonatomic,weak) IBOutlet UIButton *btnleixing;
@property (nonatomic,weak) IBOutlet UIButton *btnDefaults;

@property(nonatomic,strong) NSMutableArray *cityArr;
@property(nonatomic,strong) NSMutableArray *areaArr;
@property(nonatomic,strong) NSArray *currentAreaArr;

@property (nonatomic,weak) IBOutlet UIImageView *addressImageView;
@property (nonatomic, strong) FSDropDownMenu *menu;
@property (nonatomic, assign) BOOL isShowAddressList;

@property (nonatomic,weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *typeImageView;
@property (strong, nonatomic) SingleTableView *distanceSingleTableView;

@property (nonatomic, weak) IBOutlet UIImageView *defaultImageView;
@property (strong, nonatomic) SingleTableView *defaultsSingleTableView;
@property (nonatomic, weak) IBOutlet UIWebView *webView;
@property WebViewJavascriptBridge* bridge;
@property (nonatomic, strong) NSArray *requestArray;
@property (nonatomic, strong) NSString *typeID;
@property (nonatomic, strong) NSString *defaultID;
@property (nonatomic, strong) NSString *districtID;
@property (nonatomic, strong) NSString *districtName;

@property (nonatomic, strong) NSString *categoryID;
@property (strong, nonatomic) SingleTableView *selectCityTableView;

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;

@end

@implementation CommityListViewController

-(instancetype)initWithDistrictID:(NSString *)DistrictID andDistrictName:(NSString *)DistrictName
{
    self = [super init];
    if (self) {
        self.districtID = DistrictID;
        self.districtName = DistrictName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"全部商区";
    [self addBackButton];
    
    [self.btnAddress setTitle:self.districtName forState:UIControlStateNormal];
    //初始化位置管理器
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jumpToOrderGoods:) name:@"JUMPTOGOODS_DETAIL" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jumpToOrderSupplier:) name:@"JUMPTOSUPPLIER_DETAIL" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAddressStatues) name:@"isShowAddressList" object:nil];
    
    self.cityArr = [[NSMutableArray alloc]init];
    self.areaArr = [[NSMutableArray alloc]init];
//    self.areaArr = @[
//                 @[@"附近",@"500米",@"1000米",@"2000米",@"5000米"],
//                 @[@"徐家汇",@"人民广场",@"陆家嘴"],
//                 @[@"三里屯",@"亚运村",@"朝阳公园"],
//                 @[@"同城"],
//                 ];
//    self.currentAreaArr = _areaArr[0];
//    FSDropDownMenu *menu = [[FSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 44) andHeight:300];
//    menu.transformView = self.addressImageView;
//    menu.tag = 1001;
//    menu.dataSource = self;
//    menu.delegate = self;
//    [self.view addSubview:menu];
    
    if (_bridge) { return; }
    
    //    UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    //    [self.view addSubview:webView];
    
    [WebViewJavascriptBridge enableLogging];
    
    _bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"ObjC received message from JS: %@", data);
        responseCallback(@"Response for message from ObjC");
    }];
    
    [_bridge registerHandler:@"WebViewJavascriptBridgeReady" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"WebViewJavascriptBridgeReady called: %@", data);
        responseCallback(@"Response from testObjcCallback");
    }];
    self.typeID = @"0";
    self.defaultID = @"1";
    NSString *url = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/%@/category/%@/supplier/1/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.districtID,self.typeID];
    [self loadExamplePage:self.webView WithUrl:url];
    
    [self webRequest_getTypeMessage];
}

-(void)viewWillAppear:(BOOL)animated
{
    NSString *url = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/%@/category/%@/supplier/1/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.districtID,self.typeID];
    [self loadExamplePage:self.webView WithUrl:url];
}

#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    //    CLLocation *currentLocation = [INTULocationManager sharedInstance].currentLocation;
    
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"city_code"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [self webRequest_citydataWithCityID:str];
        }else{
            
        }
    }];
}

//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorMsg = nil;
    if ([error code] == kCLErrorDenied) {
        errorMsg = @"访问被拒绝";
    }
    if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = @"获取位置信息失败";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
                                                       message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
    [alertView show];
}

-(void)webRequest_citydataWithCityID:(NSString *)sendeid
{
    NSString *getPul = @"";
    NSString *cityID = [KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID];
    if (cityID) {
        getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,cityID];
    }else{
        getPul = [NSString stringWithFormat:@"%@/%@",KInterface_getRegion,sendeid];
    }
    [SVProgressHUD showWithStatus:@"请稍后..." maskType:SVProgressHUDMaskTypeClear];
    [HttpRequestManager getMethod:getPul parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            [SVProgressHUD dismiss];
            [[selectDistrict shardDistrictInfo]setClasscityArray:response[@"value"]];
            [self.cityArr addObject:@"全部商区"];
            [self.areaArr addObject:@"0"];
            [self.cityArr addObjectsFromArray:[selectDistrict shardDistrictInfo].DistrictNameArray];
            [self.areaArr addObjectsFromArray:[selectDistrict shardDistrictInfo].DistrictIdArray];
        }else{
            DLog(@"%@",errMsg);
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}


-(void)loadExamplePage:(UIWebView *)webView WithUrl:(NSString *)url
{
    NSString *strUrl = url;
    NSURL *urls = [NSURL URLWithString:[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //    webView.delegate = self;
    [webView loadRequest:[NSURLRequest requestWithURL:urls]];

}

-(void) webViewDidFinishLoad:(UIWebView *)webView {
    
    //    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
    
//    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    //    DLog(@"1111111111%@",title);
    
}

-(void)webRequest_getTypeMessage
{
    [HttpRequestManager getMethod:KinterFace_CategorySupplier parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            self.requestArray = [[NSArray alloc]initWithArray:response[@"value"]];
            DLog(@"%@",response);
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

-(void)jumpToOrderGoods:(NSNotification *)noti
{
    WaresDetailViewController *waresDetailVC = [[WaresDetailViewController alloc]initWithCommodityID:[noti object]];
    [self.navigationController pushViewController:waresDetailVC animated:YES];
}

-(void)jumpToOrderSupplier:(NSNotification *)noti
{
    RepairAndHomeViewController *repairAndHomeVC = [[RepairAndHomeViewController alloc]initWithMerchantID:[noti object]];
    [self.navigationController pushViewController:repairAndHomeVC animated:YES];
}

-(IBAction)selectAddress_Touch:(id)sender
{
    if(self.btnAddress.selected == NO)
    {
        self.btnAddress.selected = YES;
    }else
    {
        self.btnAddress.selected = NO;
    }
    self.btnleixing.selected = NO;
    self.btnDefaults.selected = NO;
    [self.selectCityTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.selectCityTableView.dataArray = self.cityArr;
}

-(IBAction)selectAllleixing:(id)sender{
    if (self.isShowAddressList == YES) {
        [self.menu menuTapped];
        self.isShowAddressList = NO;
    }

    if(self.btnleixing.selected == NO)
    {
        self.btnleixing.selected = YES;
    }else{
        self.btnleixing.selected = NO;
    }
    self.btnAddress.selected = NO;
    self.btnDefaults.selected = NO;
    
    [self.distanceSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    NSMutableArray *arrdata = [[NSMutableArray alloc]init];
    [arrdata addObject:@"全部类型"];
    [self.requestArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
        [arrdata addObject:obj[@"name"]];
    }];
    self.distanceSingleTableView.dataArray = arrdata;
}

-(IBAction)selectDefaults_Touch:(id)sender
{
    if (self.isShowAddressList == YES) {
        [self.menu menuTapped];
        self.isShowAddressList = NO;
    }
    
    if(self.btnDefaults.selected == NO)
    {
        self.btnDefaults.selected = YES;
    }else{
        self.btnDefaults.selected = NO;
    }
    self.btnAddress.selected = NO;
    self.btnleixing.selected = NO;

    [self.defaultsSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.defaultsSingleTableView.dataArray = @[@"默认浏览",@"只看商品",@"只看商户"];
}

-(void)changeAddressStatues
{
    self.isShowAddressList = NO;
}

#pragma mark - singleTableViewDelegate
- (SingleTableView *)distanceSingleTableView
{
    if (!_distanceSingleTableView) {
        _distanceSingleTableView = [[SingleTableView alloc] init];
        _distanceSingleTableView.delegate = self;
        [self addChildViewController:_distanceSingleTableView];
        [self.view addSubview:_distanceSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _distanceSingleTableView.arrawImageView = self.typeImageView;
    }
    return _distanceSingleTableView;
}

- (SingleTableView *)selectCityTableView
{
    if (!_selectCityTableView) {
        _selectCityTableView = [[SingleTableView alloc] init];
        _selectCityTableView.delegate = self;
        [self addChildViewController:_selectCityTableView];
        [self.view addSubview:_selectCityTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _selectCityTableView.arrawImageView = self.addressImageView;
    }
    return _selectCityTableView;
}

- (void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.btnAddress.selected = NO;
    self.btnleixing.selected = NO;
    self.btnDefaults.selected = NO;
    if (tableView == self.distanceSingleTableView) {
        NSMutableArray *dataArr = [[NSMutableArray alloc]init];
        NSMutableArray *dataId = [[NSMutableArray alloc]init];
        [dataArr addObject:@"全部类型"];
        [dataId addObject:@"0"];
        [self.requestArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
            [dataArr addObject: obj[@"name"]];
            [dataId addObject:obj[@"id"]];
        }];
        NSString *celltest = dataArr[indexPath.row];
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.btnleixing setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.btnleixing setTitle:celltest forState:UIControlStateNormal];
            
        }
        self.typeID = dataId[indexPath.row];
        NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/1301/category/%@/supplier/%@/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.typeID,self.defaultID];
        
        [self loadExamplePage:self.webView WithUrl:stringUrl];
        
//        [self.btnleixing setTitle:celltest forState:UIControlStateNormal];
    }else if(tableView == self.defaultsSingleTableView)
    {
        NSString *celltest =@[@"默认浏览",@"只看商品",@"只看商户"][indexPath.row];
        [self.btnDefaults setTitle:celltest forState:UIControlStateNormal];
        self.defaultID = @[@"0",@"1",@"2"][indexPath.row];
        if ([self.defaultID intValue] == 0) {
            NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/1301/category/%@/supplier/1/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.typeID];
            [self loadExamplePage:self.webView WithUrl:stringUrl];

        }else if([self.defaultID intValue] == 1){
            NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/1301/category/%@/supplier/0/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.typeID];
            [self loadExamplePage:self.webView WithUrl:stringUrl];

        }else{
        NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/1301/category/%@/supplier/1/goods/0",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.typeID];
            [self loadExamplePage:self.webView WithUrl:stringUrl];

        }
    }else{
        [self.btnAddress setTitle:self.cityArr[indexPath.row] forState:UIControlStateNormal];
        self.categoryID = self.areaArr[indexPath.row];
        if ([self.areaArr[indexPath.row] intValue]== 0) {
            NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/category/%@/supplier/1/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.typeID];
            [self loadExamplePage:self.webView WithUrl:stringUrl];

        }else{
        NSString *stringUrl = [NSString stringWithFormat:@"http://api.icszx.com/resource/street/city/%@/district/%@/category/%@/supplier/1/goods/1",[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122",self.categoryID,self.typeID];
        [self loadExamplePage:self.webView WithUrl:stringUrl];
        }
    }
}

-(void)senderCancle
{
    self.btnAddress.selected = NO;
    self.btnleixing.selected = NO;
    self.btnDefaults.selected = NO;
}

-(void)cancleTabelView
{
    self.btnAddress.selected = NO;
    self.btnleixing.selected = NO;
    self.btnDefaults.selected = NO;
}

- (SingleTableView *)defaultsSingleTableView
{
    if (!_defaultsSingleTableView) {
        _defaultsSingleTableView = [[SingleTableView alloc] init];
        _defaultsSingleTableView.delegate = self;
        [self addChildViewController:_defaultsSingleTableView];
        [self.view addSubview:_defaultsSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _defaultsSingleTableView.arrawImageView = self.defaultImageView;
    }
    return _defaultsSingleTableView;
}

#pragma mark - reset button size

-(void)resetItemSizeBy:(NSString*)str{
//    [self.btnAddress setTitleColor:[UIColor colorWithWhite:0.580 alpha:1.000] forState:UIControlStateNormal];
    [self.btnAddress setTitle:str forState:UIControlStateNormal];
}


#pragma mark - FSDropDown datasource & delegate

- (NSInteger)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == menu.rightTableView) {
        return _cityArr.count;
    }else{
        return _currentAreaArr.count;
    }
}
- (NSString *)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView titleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == menu.rightTableView) {
        
        return _cityArr[indexPath.row];
    }else{
        return _currentAreaArr[indexPath.row];
    }
}


- (void)menu:(FSDropDownMenu *)menu tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView == menu.rightTableView){
        _currentAreaArr = _areaArr[indexPath.row];
        [menu.leftTableView reloadData];
    }else{
        self.isShowAddressList = NO;
        self.btnAddress.selected = NO;
        self.btnleixing.selected = NO;
        self.btnDefaults.selected = NO;
        [self resetItemSizeBy:_currentAreaArr[indexPath.row]];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
